package com.pqtest.api.domain;

import com.pqtest.api.entity.AccountEntity;
import com.pqtest.api.service.UserService;

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;

@Component
public class IdentifyDomain implements UserDetailsService {
    @Getter @Setter
    private String password;
    @Autowired
    UserService userService;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String reqPwd = request.getParameter("password");
        String grantType = request.getParameter("grant_type");
        //for unit test
        if(reqPwd == null){
            if(grantType.equals("password")){
                throw new UsernameNotFoundException("Account not exists");
            } else{
                reqPwd = "";
            }
        }
        //refersh_token
        if(s.indexOf("_") > -1){
            s = s.split("_")[1];
        }
        AccountEntity u = userService.getAccountByName(s);
        if(u.equals(null)){
            throw new UsernameNotFoundException("Account not exists");
        }
        String fmd5 = DigestUtils.md5DigestAsHex(reqPwd.getBytes()) + u.getSalt();
       // System.out.println(DigestUtils.md5DigestAsHex(fmd5.getBytes()));
        if(u == null){
            throw new UsernameNotFoundException("Account not exists");
        }
        else if(grantType.equals("password") && !DigestUtils.md5DigestAsHex(fmd5.getBytes()).equals(u.getPassword())){
//        } if(!DigestUtils.md5DigestAsHex(getPassword().getBytes()).equals(u.getPassword())){
            throw new UsernameNotFoundException("AccountDto not exists");
        }
        else {
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            return new User(u.getId()+"_"+u.getName(),encoder.encode(reqPwd),Collections.EMPTY_SET);
        }
    }

   // public AccountDto
}
